package com.bbm.communitysystem.controller.role;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bbm.communitysystem.core.domain.R;
import com.bbm.communitysystem.domain.Per;
import com.bbm.communitysystem.domain.dto.role.PerDto;
import com.bbm.communitysystem.domain.vo.PageVo;
import com.bbm.communitysystem.domain.vo.PerVo;
import com.bbm.communitysystem.service.IPerService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author bbm
 * @since 2025-02-13
 */
@Tag(name = "API管控")
@Slf4j
@RestController
@RequestMapping("/per")
@RequiredArgsConstructor
public class PerController {

    private final IPerService perService;

    @Operation(summary = "新增API")
    @PostMapping("/")
    public R<String> addPer(@RequestBody PerDto perDto) {
        return perService.addPer(perDto) == 0 ? R.ok("新增成功") : R.error("新增失败");
    }

    @Operation(summary = "删除API")
    @DeleteMapping("/")
    public R<String> deletePer(@RequestParam("id") Integer id) {
        return perService.delPer(id) == 0 ? R.ok("删除成功") : R.error("删除失败");
    }

    @Operation(summary = "更新API")
    @PutMapping("/")
    public R<String> updatePer(@RequestBody PerDto perDto) {
        return perService.putPer(perDto) == 0 ? R.ok("更新成功") : R.error("更新失败");
    }

    @Operation(summary = "获取API")
    @GetMapping("/")
    public R<Per> getPer(@RequestParam("id") Integer id) {

        Per per = perService.getById(id);

        if (per == null) {
            return R.error("获取失败");
        }

        return R.ok(per);
    }

    @Operation(summary = "获取API列表")
    @GetMapping("/list")
    public R<PageVo<PerVo>> getPerList(@RequestParam("page") Integer page, @RequestParam("size") Integer size) {

        Page<Per> perPage = new Page<>(page, size);
        perService.page(perPage);

        PageVo<PerVo> pageVo = new PageVo<>(perPage);

        perPage.getRecords().forEach(item -> {
            PerVo perVo = new PerVo();
            perVo.setId(item.getId());
            perVo.setPerName(item.getPerName());
            perVo.setPerPath(item.getPerPath());
            perVo.setPerMod(item.getPerMod());
            perVo.setDescription(item.getPerDescription());
            perVo.setUpdateBy(item.getUpdateBy());
            perVo.setUpdateTime(item.getUpdateTime());
            perVo.setStatus(item.getStatus());
            pageVo.getRecords().add(perVo);
        });

        return R.ok("获取成功", pageVo);
    }

}
